using System;
using System.Data;
using System.Text;
using System.Windows.Forms;

using ctsu.BaseForms;
using ctsu.Data;

namespace ctsu.Admin.BusLogic.CoreLab
{

	public class SearchSamplesController : SearchController
	{
		public SearchSamplesController(FormSearchBase form, SearchInfo si)
			: base(form, si)
		{

		}

		public override void RunSearch(object sender, System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Cursor.Current = Cursors.WaitCursor;

			if (_form.SearchFields.SelectedIndex == -1)
			{
				MessageBox.Show(_form, "You must select a field to search by!", "Select Search By", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}
			string searchByField = ((ReportColumn)_form.SearchFields.SelectedItem).FieldName;

			StringBuilder sql = new StringBuilder("");

			if (this._si.SqlCommand.Length > 0)
				sql.Append(this._si.SqlCommand);
			else
			{
				sql.Append("SELECT ");
				//build select fields part
				foreach (ReportColumn rc in _si.SearchResultCols)
				{
					sql.Append(rc.FieldName + ",");
				}
				sql.Remove(sql.Length - 1, 1);
				sql.Append(" FROM " + _si.TableName);
			}

			string criteria = "";
			criteria = _form.Criteria.Text;

			//add there where for the select statement
			if (criteria.Length > 0)
			{
				//need schema info to build where part
				DataColumn dc = _si.TableSchema.Columns[searchByField];
				if (sql.ToString().IndexOf("WHERE") > -1)
					sql.Append(" AND " + searchByField);
				else
					sql.Append(" WHERE " + searchByField);

				if (dc.DataType == typeof(System.String))
				{
					sql.Append(" LIKE '" + criteria + "%'");
				}
				else if (dc.DataType == typeof(System.DateTime))
				{
					try
					{
						Convert.ToDateTime(criteria);
						sql.Append("='" + criteria + "'");
					}
					catch
					{
						sb.Append("Criteria is not a valid date.");
						MessageBox.Show(this._form, sb.ToString(), "Search Query Syntax Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return;
					}
				}
				else if (dc.DataType == typeof(System.Int32))
				{
					try
					{
						Convert.ToInt32(criteria);
						sql.Append("=" + criteria);
					}
					catch
					{
						sb.Append("Criteria is not a valid number.");
						MessageBox.Show(this._form, sb.ToString(), "Search Query Syntax Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return;
					}


				}
				else
					sql.Append("=" + criteria);
			}
			else
			{
				if (_si.Name == "DrawLabel")
					sql.Append(" WHERE BatchInNum > 0");
				//				if(_si.Name == "DrawBatch")									
				//					sql.Append(" WHERE ID > 0");				
				if (_si.Name == "TestLabel")
					sql.Append(" WHERE IsLegacy != 1 OR IsLegacy IS NULL");
				if (_si.Name == "TestInBatch")
					sql.Append(" WHERE IsLegacy = 0");
				if (_si.Name == "LegacyLabel")
					sql.Append(" WHERE IsLegacy=1");
				if (_si.Name == "TestInBatchLegacy")
					sql.Append(" WHERE IsLegacy=1");
				if (_si.Name == "TestOutLabel")
					sql.Append(" WHERE BatchOutNum>0");
				if (_si.Name == "EditBatchLabel")
					sql.Append(" WHERE BatchID>0");
			}

			//add order by
			sql.Append(" ORDER BY " + searchByField);
			if (this._form.Descending.Checked)
				sql.Append(" DESC ");

			//clear the listview and fill with results
			_form.SearchResults.BeginUpdate();
			_form.SearchResults.Items.Clear();

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());

				while (reader.Read())
				{
					if (_si.Name == "DrawLabel")
					{
						int batch = reader.GetInt32(0);
						if (batch == 0)
						{
							sb.Append("Sample: " + this._form.Criteria.Text + " is a legacy sample.");
							sb.Append(Environment.NewLine);
							sb.Append("Please use the 'Legacy Labels' screen.");
							MessageBox.Show(this._form, sb.ToString(), "Legacy Label", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return;
						}

					}
					if (_si.Name == "TestOutLabel")
					{
						if (reader.IsDBNull(0))
						{
							sb.Append("Sample: " + this._form.Criteria.Text + " has not been checked out in a batch.");
							sb.Append(Environment.NewLine);
							MessageBox.Show(this._form, sb.ToString(), "Not In Batch", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return;
						}
					}
					if (_si.Name == "TestLabel")
					{
						if (!reader.IsDBNull(2))
						{
							bool isLegacy = reader.GetBoolean(2);
							if (isLegacy)
							{
								sb.Append("Sample: " + this._form.Criteria.Text + " is a legacy sample.");
								sb.Append(Environment.NewLine);
								sb.Append("Please use the 'Legacy Labels' screen.");
								MessageBox.Show(this._form, sb.ToString(), "Legacy Label", MessageBoxButtons.OK, MessageBoxIcon.Error);
								return;
							}
						}
					}
					if (_si.Name == "TestInBatch")
					{
						if (!reader.IsDBNull(2))
						{
							bool isLegacy = reader.GetBoolean(2);
							if (isLegacy)
							{
								sb.Append("Batch: " + this._form.Criteria.Text + " is a legacy batch.");
								sb.Append(Environment.NewLine);
								sb.Append("Please use the 'Legacy Labels' screen.");
								MessageBox.Show(this._form, sb.ToString(), "Legacy Batch", MessageBoxButtons.OK, MessageBoxIcon.Error);
								return;
							}
						}
					}
					if (_si.Name == "LegacyLabel")
					{
						bool isLegacy = false;
						if (!reader.IsDBNull(2))
							isLegacy = reader.GetBoolean(2);
						if (!isLegacy)
						{
							sb.Append("Sample: " + this._form.Criteria.Text + " is not a legacy sample.");
							sb.Append(Environment.NewLine);
							sb.Append("Please use the 'Test Labels' screen.");
							MessageBox.Show(this._form, sb.ToString(), "Not Legacy Sample", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return;
						}
					}
					if (_si.Name == "TestInBatchLegacy")
					{
						bool isLegacy = false;
						if (!reader.IsDBNull(2))
							isLegacy = reader.GetBoolean(2);
						if (!isLegacy)
						{
							sb.Append("Batch: " + this._form.Criteria.Text + " is not a legacy batch.");
							sb.Append(Environment.NewLine);
							sb.Append("Please use the 'Test Labels' screen.");
							MessageBox.Show(this._form, sb.ToString(), "Not Legacy Batch", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return;
						}
					}

					ListViewItem lvi = new ListViewItem();
					int i = 0;
					string data;
					foreach (ReportColumn rc in _si.SearchResultCols)
					{
						if (reader.IsDBNull(i))
							data = "";
						else
							data = reader[rc.FieldName].ToString();
						if (i == 0)
							lvi.Text = data;
						else
							lvi.SubItems.Add(data);
						i++;
					}
					_form.SearchResults.Items.Add(lvi);
				}
				if (_form.SearchResults.Items.Count == 0)
					MessageBox.Show("No records were found.");

				if (_form.SearchResults.Items.Count == 1)
					this._form.SearchResults.Items[0].Selected = true;

				//resize the listview columns according to the results
				foreach (ColumnHeader ch in _form.SearchResults.Columns)
					ch.Width = -2;

			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Error in query syntax.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Search Query Syntax Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				_form.SearchResults.EndUpdate();
			}
		}








	}
}
